<?php

namespace app\api\controller;

use app\common\controller\Api;
use util\XRsa;
use app\admin\model\insurance\Policy;
use app\admin\model\insurance\Customer;
use fast\Http;
use think\Db;
use think\Exception;
use think\exception\ValidateException;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test', 'test1','getproject'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function test()
    {
        try {
            $config=config('site.zcy');
            $public_key=$config['public_key'];
            $private_key=$config['private_key'];
        

            // 初始化
            $rsa = new XRsa($public_key, $private_key);
            $timestamp= date('Y-m-d H:i:s');
            $params=[
                'appId'=>$config['appId'],
                'channelCode'=>$config['channelCode'],
                'charset'=>'UTF-8',
                'funcCode'=>'queryCustomerData',
                'productCode'=>$config['productCode'],
                'timestamp'=>$timestamp,
                'version'=>'1.0.0',
            ];
            $policyModel = new Policy();
            $policyData = $policyModel->alias('p')
            ->field('p.*')
            ->join('insurance_customer c', 'p.id = c.order_id', 'LEFT')
            ->whereNull('c.order_id')
            // ->where(['p.id'=>4])
            ->select();
            if(!$policyData){
                return json([
                    'message' => '未查到对应信息',
                    'code' => '99',
                    'success' => false,
                    'result' => ''
                ]);
            }
            foreach ($policyData as $key => $value) {
                if($value['customerId']== null){
                    continue;
                }
                $content=[
                    'customerId'=>$value['customerId'],
                    'applyCode'=>$value['applyCode'],
                    'channelCode'=>'ZSCX',
                    'customerBasicInfo'=>1
                ];
                $bizContent= $rsa->publicEncrypt(json_encode($content,JSON_UNESCAPED_UNICODE));
                $params['bizContent']=$bizContent;
                ksort($params);
                $sign = urldecode(http_build_query($params));
                $signature = $rsa->sign($sign);
                // 签名验证
                if($signature){
                    $params['sign']=$signature;
                    $params['signType']='RSA2';
                }
                $headers = ['Content-type: application/json'];
                $options = [
                    CURLOPT_HTTPHEADER => $headers
                ];

                $result = Http::post('https://middle-staging.zcygov.cn/api/finance/gateway/callback', json_encode($params,JSON_UNESCAPED_UNICODE), $options);
                if($result){
                    $data=json_decode($result,true);
                    if($data['success']=== false){
                        continue;
                    }
                    if(isset($data['resultContent']['result']['enterpriseName']) && $data['resultContent']['result']!==''){
                        //数据保存
                        $order = Customer::get(['order_id' => $value['id']]);
                        if (!$order) {
                            // 数据存在则更新
                            $itemsResult = Customer::add($value['id'], $data['resultContent']['result']);
                            if($itemsResult){
                                 return json([
                                    'message' => '保存成功: ',
                                    'code' => '00',
                                    'success' => true,
                                    'result' => ''
                                ]);
                            }
                           
                        }else{
                            throw new Exception( $value['id'].'供应商数据存在'); 
                        } 
                    }else{
                         continue;
                    }
                

                }
            }
        } catch (ValidateException $e) {
            trace('验证异常：' . $e->getMessage(), 'error');
            return json([
                'message' => '数据验证失败: ' . $e->getMessage(),
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        } catch (Exception $e) {
            trace('系统异常：' . $e->getMessage(), 'error');
            return json([
                'message' => '处理失败: ' . $e->getMessage(),
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        } catch (\Throwable $th) {
            trace('严重异常：' . $th->getMessage(), 'error');
            return json([
                'message' => '系统错误',
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        }

        $this->error('获取信息失败');
    }

    /**
     * 无需登录的接口
     *
     */
    public function test1()
    {
        $this->success('返回成功', ['action' => 'test1']);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }
    public function getproject()
    {
        try {
            $getdata = $this->request->param();
            $config=config('site.zcy');
            $public_key=$config['public_key'];
            $private_key=$config['private_key'];
        

            // 初始化
            $rsa = new XRsa($public_key, $private_key);
            $timestamp= date('Y-m-d H:i:s');
            $params=[
                'appId'=>$config['appId'],
                'channelCode'=>$config['channelCode'],
                'charset'=>'UTF-8',
                'funcCode'=>'queryCustomerData',
                'productCode'=>$config['productCode'],
                'timestamp'=>$timestamp,
                'version'=>'1.0.0',
            ];
            $policyModel = new Policy();
            $Data = $policyModel->alias('p')
            ->field('p.*')
            ->join('insurance_customer c', 'p.id = c.order_id', 'LEFT')
            ->whereNull('c.order_id')
            ->select();
            foreach ($Data as $key => $value) {
           
                $policyData = $policyModel->where(['projectCode'=>$value['projectCode']])->find();
                if(!$policyData){
                    $this->error('未查到对应信息');
                }
                if($policyData['customerId']== null){
                    $this->error('无供应商');
                }
                $content=[
                    'customerId'=>$policyData['customerId'],
                    'applyCode'=>$policyData['applyCode'],
                    'channelCode'=>'ZSCX',
                    'projectCode'=>$value['projectCode']
                ];
                $bizContent= $rsa->publicEncrypt(json_encode($content,JSON_UNESCAPED_UNICODE));
                $params['bizContent']=$bizContent;
                ksort($params);
                $sign = urldecode(http_build_query($params));
                $signature = $rsa->sign($sign);
                // 签名验证
                if($signature){
                    $params['sign']=$signature;
                    $params['signType']='RSA2';
                }
                $headers = ['Content-type: application/json'];
                $options = [
                    CURLOPT_HTTPHEADER => $headers
                ];

                $result = Http::post('https://middle-staging.zcygov.cn/api/finance/gateway/callback', json_encode($params,JSON_UNESCAPED_UNICODE), $options);
                if($result){
                    $data=json_decode($result,true);
                    if($data['success']=== false){
                        return json([
                            'message' => '获取订单失败',
                            'code' => '99',
                            'success' => false,
                            'result' => ''
                        ]);
                    }
                    if(isset($data['resultContent']['result']['projectInfo']) && $data['resultContent']['result']!==''){
                        //数据保存
                        $policyData->distCode = $data['resultContent']['result']['projectInfo']['distCode'];
                        // save方法会自动判断数据是否发生变化，无变化则不执行更新
                        $policyData->save();
                        return json([
                            'message' => '处理成功',
                            'code' => '00',
                            'success' => true,
                            'result' => ''
                        ]);
                        
                    }
                }
            

            }
        } catch (ValidateException $e) {
            trace('验证异常：' . $e->getMessage(), 'error');
            return json([
                'message' => '数据验证失败: ' . $e->getMessage(),
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        } catch (Exception $e) {
            trace('系统异常：' . $e->getMessage(), 'error');
            return json([
                'message' => '处理失败: ' . $e->getMessage(),
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        } catch (\Throwable $th) {
            trace('严重异常：' . $th->getMessage(), 'error');
            return json([
                'message' => '系统错误',
                'code' => '99',
                'success' => false,
                'result' => ''
            ]);
        }

        $this->error('获取信息失败');
    }

}
